package com.phiture.erp.produce.core.proxy;

import com.phiture.erp.produce.core.event.BomInfoChangedEvent;
import com.phiture.erp.produce.core.pojo.dto.MrpBomInfoDTO;
import com.phiture.erp.produce.core.service.BomService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Primary;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author YH
 * @date 2025-05-06-16:25
 * FIXME ConcurrentHashMap只适用于单体项目
 */
@Service
@Primary
@RequiredArgsConstructor
public class BomServiceCacheProxy implements BomService {
    private final BomService targetBomService;
    private final Map<Long, List<MrpBomInfoDTO>> CACHE_MAP = new ConcurrentHashMap<>();


    @Override
    public List<MrpBomInfoDTO> getBom(Long materialId) {
        if(materialId == null) return Collections.emptyList();
        return CACHE_MAP.computeIfAbsent(materialId, targetBomService::getBom);
    }

    @EventListener
    public void handleBomInfoChangedEvent(BomInfoChangedEvent event) {
        Long materialId = event.getMaterialId();
        if (materialId != null) {
            CACHE_MAP.remove(materialId);
        }
    }
}
